package com.yan.config;

import com.yan.pojo.user;
import com.yan.service.UserService;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了doGetAuthorizationInfo 授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //  info.addStringPermission("user:add");
        Subject subject = SecurityUtils.getSubject();
        user currentUser = (user) subject.getPrincipal();
        info.addStringPermission(currentUser.getPerms());
        return info;
    }


    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了 doGetAuthenticationInfo 认证");

//        String name="name";
//        String password="123456";

        UsernamePasswordToken usertoken = (UsernamePasswordToken) authenticationToken;

        user user = userService.queryUserByName(usertoken.getUsername());

        if (!usertoken.getUsername().equals(user.getName())) {
            return null; //抛出异常
        }


        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("loginuser",user);


        //密码认证
        return new SimpleAuthenticationInfo(user, usertoken.getPassword(), "");
    }
}
